package com.ruoyi.api.activiti.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.activiti.service.UsualWrokService;
import com.ruoyi.api.applycopy.domain.Applycopy;
import com.ruoyi.api.applycopy.service.IApplycopyService;
import com.ruoyi.api.mqtt.MqttService;
import com.ruoyi.api.wsmessage.domain.Wsmessage;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.history.HistoricProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service("taskExecutionListener")
@Slf4j
public class TaskExecutionListener implements ExecutionListener {
  @Autowired
  private UsualWrokService usualWrokService;
  @Autowired
  private HistoryService historyService;
  @Autowired
  private IApplycopyService applycopyService;

  @Autowired
  private ISysUserService sysUserService;
  @Autowired
  private MqttService mqttService;

  @Override
  public void notify(DelegateExecution delegateExecution) {
    System.out.println(delegateExecution);
    String eventName = delegateExecution.getEventName();
    if (eventName.equalsIgnoreCase("start")) {
      log.error("===start==" + delegateExecution.getVariables());
    } else if (eventName.equalsIgnoreCase("end")) {
      log.error("===end==" + delegateExecution.getVariables());
      Map<String, Object> variables = delegateExecution.getVariables();
      if (variables.containsKey("approved") && variables.containsKey("service")) {
        Object approved = variables.get("approved");
        Object service = variables.get("service");
        if (approved instanceof Integer && service instanceof String) {
          Integer i1 = (Integer) approved;
          String s1 = (String) service;
          String processInstanceId = delegateExecution.getProcessInstanceId();
          updateApplyEndState(s1, i1, processInstanceId);
        }
      }
    } else if (eventName.equalsIgnoreCase("take")) {
      log.error("===take==" + delegateExecution.getVariables());
    }
  }

  public void updateApplyEndState(String service, Integer approved, String processInstanceId) {
    HistoricProcessInstance hp =
      historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId)
        .includeProcessVariables().singleResult();
      //根据processInstanceId查询业务对象
      JSONObject jsonObject = usualWrokService.findByProcessInstanceId(processInstanceId, service);
      if (jsonObject == null) return;
      if (approved == 1) {
        jsonObject.put("taskName","审核通过");
        jsonObject.put("suspendState","5");

        Map<String, Object> variables = hp.getProcessVariables();
        if (variables.containsKey("copyReceivers")) {
          String copyNames = (String) variables.get("copyReceivers");
          String loginNameSender = (String) variables.get("loginNameSender");
          String copyComment = (String) variables.get("copyComment");
          String[] nameArr = copyNames.split(",");
          for (String str1 : nameArr) {
            //插入抄送数据表
            Applycopy applycopy = new Applycopy();
            applycopy.setEntityid(jsonObject.getString("id"));
            applycopy.setService(service);
            applycopy.setLoginnamereceiver(str1);
            applycopy.setLoginnamesender(loginNameSender);
            applycopy.setInstanceid(processInstanceId);
            applycopy.setCopycomment(copyComment);
            applycopyService.insertApplycopy(applycopy);
          }
        }
      }else if(approved == -2){
        jsonObject.put("taskName","作废");
        jsonObject.put("suspendState","6");
      }
      else {
        jsonObject.put("taskName","审核未通过");
        jsonObject.put("suspendState","6");
      }
        jsonObject.put("endTime",System.currentTimeMillis());
        usualWrokService.update(JSON.toJSONString(jsonObject), 1,service);
        //审批结束，发送消息给审批申请人
      String createrId = jsonObject.getString("createrId");
      long l = Long.parseLong(createrId);
      SysUser sysUser = sysUserService.selectUserById(l);

      String suspendState=jsonObject.getString("suspendState");
      String title=jsonObject.getString("title");
      if(suspendState.equalsIgnoreCase("5")){
          title=title+"-审核通过";
      }else {
          title=title+"-审批未通过";
      }

      Wsmessage wsmessage=new Wsmessage();

      String entityId=jsonObject.getString("entityId");
      wsmessage.setEntityId(entityId);
      String instanceId=jsonObject.getString("instanceId");
      wsmessage.setInstanceId(instanceId);
      String taskName=jsonObject.getString("taskName");
      wsmessage.setTaskName(taskName);
      String applyState=jsonObject.getString("applyState");
      wsmessage.setApplyState(applyState);
      String permission=jsonObject.getString("permission");
      wsmessage.setPermission(permission);
      String type=jsonObject.getString("type");
      wsmessage.setType(type);
      String typeName=jsonObject.getString("typeName");
      wsmessage.setTypeName(typeName);
      wsmessage.setUserSenderId(sysUser.getUserId());
      Long createTime = jsonObject.getLong("createTime");
      wsmessage.setSubmitTime(new Date(createTime));
      mqttService.sendMessage(1,wsmessage);

  }
}
